package com.virtualperson.service.impl;

import com.virtualperson.config.AliyunConfig;
import com.virtualperson.dto.ImageGenerationRequest;
import com.virtualperson.dto.ImageGenerationResponse;
import com.virtualperson.exception.ImageValidationException;
import com.virtualperson.service.ImageGenerationService;
import com.virtualperson.util.ImageValidationUtil;
import com.virtualperson.util.PromptValidationUtil;
import com.virtualperson.util.ParameterValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;

@Slf4j
@Service
public class ImageGenerationServiceImpl implements ImageGenerationService {

    private static final String GENERATION_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation";
    private static final String TASK_STATUS_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}";

    @Autowired
    private AliyunConfig aliyunConfig;
    
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public ImageGenerationResponse generateImage(ImageGenerationRequest request) {
        try {
            // 验证请求参数
            validateRequest(request);

            // 验证图片
            if (StringUtils.hasText(request.getInput().getBaseImageUrl())) {
                ImageValidationUtil.validateImage(request.getInput().getBaseImageUrl(), "base_image_url", false, false, false);
            }
            
            // mask图片是必选的
            if (!StringUtils.hasText(request.getInput().getMaskImageUrl())) {
                throw new ImageValidationException("mask_image_url是必选参数");
            }
            ImageValidationUtil.validateImage(request.getInput().getMaskImageUrl(), "mask_image_url", true, false, false);

            // 验证人脸图片（如果提供）
            if (StringUtils.hasText(request.getInput().getFaceImageUrl())) {
                ImageValidationUtil.validateImage(request.getInput().getFaceImageUrl(), "face_image_url", false, true, false);
            }

            // 验证背景图片（如果提供）
            if (StringUtils.hasText(request.getInput().getBackgroundImageUrl())) {
                ImageValidationUtil.validateImage(request.getInput().getBackgroundImageUrl(), "background_image_url", false, false, true);
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aliyunConfig.getAccessKeySecret());
            headers.set("X-DashScope-Async", "enable");

            // 创建请求实体
            HttpEntity<ImageGenerationRequest> requestEntity = new HttpEntity<>(request, headers);

            // 发送请求
            ResponseEntity<ImageGenerationResponse> response = restTemplate.exchange(
                GENERATION_URL,
                HttpMethod.POST,
                requestEntity,
                ImageGenerationResponse.class
            );

            ImageGenerationResponse result = response.getBody();
            if (result != null) {
                result.setSuccess(true);
            }
            return result;
        } catch (ImageValidationException e) {
            throw e;
        } catch (Exception e) {
            log.error("调用文生图服务失败", e);
            ImageGenerationResponse response = new ImageGenerationResponse();
            response.setSuccess(false);
            response.setErrorMessage(e.getMessage());
            return response;
        }
    }

    @Override
    public ImageGenerationResponse getTaskStatus(String taskId) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + aliyunConfig.getAccessKeySecret());

            // 创建请求实体
            HttpEntity<?> requestEntity = new HttpEntity<>(headers);

            // 发送请求
            ResponseEntity<ImageGenerationResponse> response = restTemplate.exchange(
                TASK_STATUS_URL,
                HttpMethod.GET,
                requestEntity,
                ImageGenerationResponse.class,
                Collections.singletonMap("taskId", taskId)
            );

            ImageGenerationResponse result = response.getBody();
            if (result != null) {
                result.setSuccess(true);
            }
            return result;
        } catch (Exception e) {
            log.error("获取任务状态失败", e);
            ImageGenerationResponse response = new ImageGenerationResponse();
            response.setSuccess(false);
            response.setErrorMessage(e.getMessage());
            return response;
        }
    }

    /**
     * 验证请求参数
     */
    private void validateRequest(ImageGenerationRequest request) {
        if (request == null) {
            throw new ImageValidationException("请求参数不能为空");
        }

        // 验证并设置默认参数
        ParameterValidationUtil.validateAndSetDefaults(request);

        // 验证必填参数
        if (request.getModel() == null || request.getModel().trim().isEmpty()) {
            throw new ImageValidationException("model参数不能为空");
        }

        if (request.getInput() == null) {
            throw new ImageValidationException("input参数不能为空");
        }

        // 验证图片URL
        if (request.getInput().getBaseImageUrl() == null || request.getInput().getBaseImageUrl().trim().isEmpty()) {
            throw new ImageValidationException("base_image_url参数不能为空");
        }
        ImageValidationUtil.validateImage(
            request.getInput().getBaseImageUrl(),
            "base_image_url",
            false,  // 不是mask图片
            false,  // 不是人脸图片
            false   // 不是背景图片
        );

        if (request.getInput().getMaskImageUrl() == null || request.getInput().getMaskImageUrl().trim().isEmpty()) {
            throw new ImageValidationException("mask_image_url参数不能为空");
        }
        ImageValidationUtil.validateImage(
            request.getInput().getMaskImageUrl(),
            "mask_image_url",
            true,   // 是mask图片
            false,  // 不是人脸图片
            false   // 不是背景图片
        );

        if (request.getInput().getFaceImageUrl() == null || request.getInput().getFaceImageUrl().trim().isEmpty()) {
            throw new ImageValidationException("face_image_url参数不能为空");
        }
        ImageValidationUtil.validateImage(
            request.getInput().getFaceImageUrl(),
            "face_image_url",
            false,  // 不是mask图片
            true,   // 是人脸图片
            false   // 不是背景图片
        );

        // 验证可选的背景图片URL
        if (request.getInput().getBackgroundImageUrl() != null && !request.getInput().getBackgroundImageUrl().trim().isEmpty()) {
            ImageValidationUtil.validateImage(
                request.getInput().getBackgroundImageUrl(),
                "background_image_url",
                false,  // 不是mask图片
                false,  // 不是人脸图片
                true    // 是背景图片
            );
        }

        // 验证提示词
        if (request.getInput().getPrompt() != null && !request.getInput().getPrompt().trim().isEmpty()) {
            PromptValidationUtil.validatePrompt(request.getInput().getPrompt(), "prompt");
        }

        if (request.getInput().getFacePrompt() == null || request.getInput().getFacePrompt().trim().isEmpty()) {
            throw new ImageValidationException("face_prompt参数不能为空");
        }
        PromptValidationUtil.validatePrompt(request.getInput().getFacePrompt(), "face_prompt");

        // 验证bgstyle_scale参数
        try {
            ParameterValidationUtil.validateBgstyleScale(request.getParameters().getBgstyleScale());
        } catch (ImageValidationException e) {
            throw new ImageValidationException("bgstyle_scale参数验证失败: " + e.getMessage());
        }

        // 验证realPerson参数
        request.getInput().setRealPerson(
            ParameterValidationUtil.validateRealPerson(request.getInput().getRealPerson())
        );

        // 验证n参数
        try {
            request.getParameters().setN(
                ParameterValidationUtil.validateN(request.getParameters().getN())
            );
        } catch (ImageValidationException e) {
            throw new ImageValidationException("n参数验证失败: " + e.getMessage());
        }

        // 验证short_side_size参数
        try {
            request.getParameters().setShortSideSize(
                ParameterValidationUtil.validateShortSideSize(
                    request.getParameters().getShortSideSize(),
                    request.getModel()
                )
            );
        } catch (ImageValidationException e) {
            throw new ImageValidationException("short_side_size参数验证失败: " + e.getMessage());
        }
    }
} 